<template>
  <el-dialog
    width="800px"
    :model-value="dialogFormVisible"
    :close-on-click-modal="false"
    append-to-body
    :before-close="close"
    :title="title"
    class="system"
  >
    <div
      style="display: flex; justify-content: space-between"
      v-loading="loading"
    >
      <div class="systemInfo">
        <p class="line">基本信息</p>
        <el-form
          ref="formRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="系统名称" prop="app_name" class="form-item">
            <el-input v-model="ruleForm.app_name" clearable />
          </el-form-item>
          <el-form-item label="系统链接" prop="app_url" class="form-item">
            <el-input v-model="ruleForm.app_url" clearable />
          </el-form-item>
          <el-form-item
            label="负责人"
            prop="app_productor_id"
            class="form-item"
          >
            <el-cascader
              :options="orgUserList"
              v-model="ruleForm.app_productor_id"
              clearable
              filterable
              style="width: 270px"
            />
          </el-form-item>
          <el-form-item label="系统简介" prop="app_desc">
            <el-input
              v-model="ruleForm.app_desc"
              type="textarea"
              maxlength="50"
              :rows="5"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="department">
        <p class="line">可见范围</p>
        <el-input
          v-model="bumenSearchInput"
          clearable
          placeholder="请输入内容"
        />
        <el-tree
          class="bumenTree"
          ref="bumenTree"
          :data="allDepartment"
          :default-checked-keys="department_list"
          show-checkbox
          node-key="value"
          :filter-node-method="filterNode"
          @check="handleCheckedBumenAndUser"
        ></el-tree>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit(formRef)"
          :loading="btnLoading"
        >
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { computed, watch } from 'vue';
import useUserStore from '@/store/modules/user';
import {
  postAddAppConf,
  postUpdateAppConf,
  postGetAppDetail
} from '@/api/systemList';
const userStore = useUserStore();
const orgUserList = userStore.orgUserList;
const allDepartment = userStore.allDepartment;
const loading = ref(false);
const btnLoading = ref(false);
const bumenSearchInput = ref('');
const departmentAllMap = ref({});
const department_list = ref([]);
const formRef = ref(null);
const bumenTree = ref(null);
const ruleForm = reactive({
  app_name: '',
  app_url: '',
  app_productor_id: null,
  app_desc: ''
});
const rules = reactive({
  app_name: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
  app_url: [{ required: true, message: '请输入系统链接', trigger: 'blur' }],
  app_productor_id: [
    {
      required: true,
      message: '请选择负责人',
      trigger: 'change'
    }
  ],
  app_desc: [{ required: true, message: '请输入系统简介', trigger: 'blur' }]
});
const props = defineProps(['dialogFormVisible', 'title', 'row']);
const emit = defineEmits(['close', 'updateData']);
const dialogFormVisible = computed({
  get: () => props.dialogFormVisible
});
const title = computed({
  get: () => props.title
});
const row = computed({
  get: () => props.row
});
const close = () => {
  formRef.value.resetFields();
  emit('close');
};
watch(bumenSearchInput, (newValue, oldValue) => {
  bumenTree.value.filter(newValue);
});
// 默认赋值
watch(dialogFormVisible, (newValue, oldValue) => {
  if (newValue === true) getAppDetail();
});
// 查询系统详情
const getAppDetail = () => {
  setTimeout(() => {
    bumenTree.value.setCheckedKeys([]);
  }, 10);
  if (!row.value.id) return;
  loading.value = true;
  postGetAppDetail({ id: row.value.id })
    .then(res => {
      loading.value = false;
      ruleForm.app_name = res.data?.app_conf.app_name;
      ruleForm.app_url = res.data?.app_conf.app_url;
      ruleForm.app_productor_id = res.data?.app_conf.app_productor_id;
      ruleForm.app_desc = res.data?.app_conf.app_desc;
      department_list.value = res.data.department_list;
    })
    .finally(() => {
      loading.value = false;
    });
};

//设置部门tree为一个map()
function departmentMap(data) {
  data.forEach(e => {
    departmentAllMap.value[e.value] = e;
    if (e.children && e.children.length) {
      departmentMap(e.children);
    }
  });
}
// 字符转小写
function getToLowerCase(val) {
  if (val) return val.toLowerCase();
  else return '';
}
const filterNode = (value, data, node) => {
  if (!value) return true;
  // 顶层父级直接判断
  if (node.level === 1) {
    let label = getToLowerCase(data.label);
    return label.indexOf(getToLowerCase(value)) !== -1;
  }
  // level > 1 递归判断父级是否包含搜索项
  return deepFilter(value, node);
};
function deepFilter(value, node) {
  if (node.level > 0) {
    let label = getToLowerCase(node.data.label);
    if (label.indexOf(getToLowerCase(value)) !== -1) {
      return true;
    }
    return deepFilter(value, node.parent);
  }
  return false;
}
const handleCheckedBumenAndUser = () => {
  department_list.value = bumenTree.value.getCheckedKeys();
  // 循环当前选中得所有节点（包含父节点）
  department_list.value?.forEach(e => {
    if (departmentAllMap.value[e] && departmentAllMap.value[e].children) {
      // 判断当前得节点是否包含子节点 如果包含直接删除选中节点中的子节点
      handleSplice(departmentAllMap.value[e].children);
    }
  });
};
function handleSplice(data) {
  data.forEach(e => {
    var index = department_list.value.indexOf(e.value);
    if (index > -1) {
      department_list.value.splice(index, 1);
    }
    if (e.children) {
      handleSplice(e.children);
    }
  });
}
const onSubmit = formEl => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      let app_productor_id = Array.isArray(ruleForm.app_productor_id)
        ? ruleForm.app_productor_id[ruleForm.app_productor_id.length - 1]
        : ruleForm.app_productor_id;
      const params = {
        app_name: ruleForm.app_name,
        app_desc: ruleForm.app_desc,
        app_productor_id: app_productor_id,
        app_url: ruleForm.app_url,
        department_list: department_list.value
      };
      if (row.value.id) {
        //修改
        params.id = row.value.id;
        updateAppConf(params);
      } else {
        //新增
        addAppConf(params);
      }
    } else {
    }
  });
};
// 新增
const addAppConf = params => {
  btnLoading.value = true;
  postAddAppConf(params)
    .then(res => {
      ElMessage.success('新增成功！');
      btnLoading.value = false;
      close();
      emit('updateData');
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
// 修改
const updateAppConf = params => {
  btnLoading.value = true;
  postUpdateAppConf(params)
    .then(res => {
      ElMessage.success('修改成功！');
      btnLoading.value = false;
      close();
      emit('updateData');
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
onMounted(() => {
  if (allDepartment) departmentMap(allDepartment);
});
</script>

<style>
.system .el-dialog__body {
  padding-top: 10px !important;
}
</style>
<style lang="scss" scoped>
.systemInfo {
  width: 350px;
  .form-item {
    margin-bottom: 30px;
  }
}
.line {
  border-left: 1px solid #008080;
  padding-left: 6px;
}
.department {
  width: 350px;
  overflow: hidden;
  .bumenTree {
    height: 280px;
    overflow: auto;
  }
}
</style>
